package com.chuangke.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.framework.model.BasicModel;
import com.chuangke.system.dao.mapper.SysConfigTypeMapper;
import com.chuangke.system.entity.SysConfig;
import com.chuangke.system.entity.SysConfigType;
import com.chuangke.system.service.SysConfigService;
import com.chuangke.system.service.SysConfigTypeService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysConfigTypeServiceImpl implements SysConfigTypeService {

	@Autowired
	private SysConfigTypeMapper sysConfigTypeMapper;

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_CONFIG_TYPE, key = "'" + CacheKeyConstants.SYS_CONFIG_TYPE + "'")
	@Override
	public void save(SysConfigType record) {
		sysConfigTypeMapper.insert(record);
	}

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_CONFIG_TYPE, key = "'" + CacheKeyConstants.SYS_CONFIG_TYPE + "'")
	@Override
	public void delete(String id) {
		sysConfigTypeMapper.deleteById(id);
	}

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_CONFIG_TYPE, key = "'" + CacheKeyConstants.SYS_CONFIG_TYPE + "'")
	@Override
	public void update(SysConfigType record) {
		sysConfigTypeMapper.updateById(record);
	}

	@Cacheable(cacheNames = CacheKeyConstants.SYS_CONFIG_TYPE, key = "'" + CacheKeyConstants.SYS_CONFIG_TYPE + "'")
	@Override
	public Map<String, SysConfigType> findAll() {
		List<SysConfigType> list = sysConfigTypeMapper.selectList(new QueryWrapper<>());
		return list == null ? new HashMap<>()
				: list.stream().collect(Collectors.toMap(BasicModel::getId, a -> a));
	}

	@Override
	public SysConfig find(String id) {
		Map<String, SysConfig> map = ((SysConfigService) AopContext.currentProxy()).findAll();
		return map == null ? null : map.get(id);
	}

}
